﻿using System;
using System.Collections.Generic;
using System.Linq;
using Nxg.Blog.Core.Documents;

namespace Nxg.Blog.Core.ViewProjections.Home {
    public class TaggedBlogPostsViewModel {
        public IEnumerable<BlogPost> Posts { get; set; }

        public string Tag { get; set; }
    }

    public class TaggedBlogPostsBindingModel {
        public string Tag { get; set; }
    }

    public class TaggedBlogPostsViewProjection : IViewProjection<TaggedBlogPostsBindingModel, TaggedBlogPostsViewModel> {
        private readonly DataContext _context;

        public TaggedBlogPostsViewProjection (DataContext context) {
            _context = context;
        }

        public TaggedBlogPostsViewModel Project (TaggedBlogPostsBindingModel input) {
            var posts = _context.Post.Where (x => x.Status == PublishStatus.Published && x.PubDate <= DateTime.Now && x.Tags.Contains (input.Tag)).OrderByDescending (x => x.PubDate).ToList ();

            if (posts.Count == 0)
                return null;
            var tagName = _context.Tag.FirstOrDefault (x => x.Slug == input.Tag)?.Name ?? input.Tag;
            return new TaggedBlogPostsViewModel {
                Posts = posts,
                    Tag = tagName
            };
        }
    }
}